package cn.suimg.shortlink.request;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;


/**
 * 基础控制器
 */
public class BasicController extends RequestUtil{

    /**
     * Logger
     */
    protected Logger logger = LoggerFactory.getLogger(this.getClass());



    /**
     * 重定向到某个页面
     *
     * @param url
     */
    protected void redirect(String url) {
        try {
            getResponse().sendRedirect(url);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    protected void forward(String url){
        try {
            getRequest().getRequestDispatcher(url).forward(getRequest(),getResponse());
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    protected void forward404(){
        forward("/error/404.do");
    }

    /**
     * 设置自动关闭浏览器窗口
     *
     * @param text
     * @return
     */
    protected String setAutoCloseWindow(String text) {
        return "<h2>" + text + "</h2><script>setTimeout(function(){window.close()},2500)</script>";
    }

    /**
     * 给页面传递登录信息
     * @param authorized
     */
    protected void authorized(Object authorized){
        getRequest().setAttribute("authorized",authorized);
    }

    /**
     * 设置页面标题
     *
     * @param title
     */
    protected void setTitle(String title) {
        getRequest().setAttribute("title", title);
    }

    /**
     * SEO:keywords
     *
     * @param keywords
     */
    protected void setKeywords(String keywords) {
        if(keywords.length()>200){
            keywords = keywords.substring(0,200);
        }
        getRequest().setAttribute("keywords", "碎梦云,Suimg,"+keywords);
    }

    /**
     * SEO:description
     *
     * @param description
     */
    protected void setDescription(String description) {
        description = description.replaceAll("\n", " ");
        if(description.length()>200){
            description = description.substring(0,200)+ "...";
        }
        getRequest().setAttribute("description", description);
    }


}
